'''
Created on 26.10.2012

@author: doleynik
'''
import cgi
import time
import json

import webapp2

from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, charges_key
from common import functions
from wtforms.ext.appengine.db import model_form

from BaseHandler import BaseHandler

class ChargesKeys(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(ChargesKeys, self).__init__(*args, **kwargs)
        self.fields = {
                       'code': _('Code'), 'name': _('Title'), 'th_tantiem_sum': _('Total Theoretical Tantieme'),
                       'immeuble': _('Tenement')
                       }

    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_list(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        template_values = {
                           'title': _('Charges keys'),
                           'header': _('%(name)s. Charges keys', name=imm.name),
                           'immeuble': imm,
                           'app_user': au,
                           'lurl': users.create_logout_url('/'),
                           'section': 'parametrage',
                           'leftmenu': 'charges_keys',
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/charges_keys.html')
        self.response.out.write(template.render(template_values))
    
    def op_list_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        charges_keys = imm.get_charges_key_list()
        ck = []
        for c in charges_keys:
            ck.append([unicode(c.code), unicode(c.name), str(c.th_tantiem_sum), str(c.key())])
        ret = {}
        ret['aaData'] = ck
        self.response.out.write(json.dumps(ret))
    
    def op_list_names_json(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        charges_keys = imm.get_charges_key_list()
        ck = []
        for c in charges_keys:
            ck.append(str(c))
        self.response.out.write(json.dumps(ck))
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        
        CKForm = model_form(charges_key, exclude=['lastchange_by', 'immeuble'])
        
        if self.request.method == 'GET':
            form = CKForm()
        
        if self.request.method == 'POST':
            form = CKForm(self.request.POST)
            
            if form.validate():
                new_charge_key = charges_key(key_name = form['code'].data + "_" + str(imm.key().id()),
                                              immeuble = imm, 
                                              code = form['code'].data, 
                                              name = form['name'].data,
                                              th_tantiem_sum = form['th_tantiem_sum'].data, 
                                              lastchange_by = au
                                              )
                new_charge_key.put()
                while not new_charge_key.is_saved():
                    time.sleep(2)
                ok_message = _('Charges key was added.')
        
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    
    def op_edit(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        ck_id = kwargs.get('ck_id', -1)
        ok_message = ''
        
        au = functions.GetAPNETUser()
        if not au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        edit_charges_key = charges_key.get(ck_id)
        
        CKForm = model_form(charges_key, exclude=['lastchange_by', 'immeuble'])
        if self.request.method == 'GET':
            form = CKForm(obj=edit_charges_key)
            
        if self.request.method == 'POST':
            form = CKForm(self.request.POST)
            
            if form.validate():
                form.populate_obj(edit_charges_key)
                edit_charges_key.lastchange_by = au
                edit_charges_key.put()
                while not edit_charges_key.is_saved():
                    time.sleep(2)
                ok_message = _('Charges key was updated.')
        
        template_values = {
                           'form': form,
                           'ok_message': ok_message,
                           'fields': self.fields
                           }
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
    

    def op_predefine(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)

        au = functions.GetAPNETUser()
        if not au:
            self.redirect(webapp2.uri_for('registration', command="user"))
            return
        
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        chargeskey_template = imm.get_prdefine_template("charges")        
        
        if self.request.method == 'POST':
            imm.set_predefine_chargeskeys(au)
            self.redirect(webapp2.uri_for('parametrage_cles', imm_id=imm_id, command='list'))
            return
        
        template_values = {
            'title': _('Charges keys template'),
            'header': _('Set of charges keys'),
            'immeuble': imm,
            'table': chargeskey_template,
            'app_user': au,
            'lurl': users.create_logout_url('/'),
            'section': 'parametrage',
            'fields': self.fields
        }
        
        template = self.jinja2.get_template('templates/charges_keys_predefine.html')
        self.response.out.write(template.render(template_values))
